﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InfiniteConvergentSeries
{
    class Program
    {
        delegate IEnumerable<double> ConvergientSeries();

        static double CalculateSum(ConvergientSeries function, double epsilon)
        {
            double sum = 0;
            double previous = 0;
            foreach (double item in function())
            {
                if (previous > 0 && previous - item < epsilon)
                {
                    break;
                }
                previous = item;
                sum += item;
            }
            return sum;
        }

        static IEnumerable<double> Function1()
        {
            Fraction fraction = new Fraction(1, 1);

            while (true)
            {
                fraction.denominator *= 2;
                yield return (double)fraction;
            }
        }

        static IEnumerable<double> Function2()
        {
            Fraction fraction = new Fraction(1, 1);
            int index = 1;

            while (true)
            {
                fraction.denominator *= index;
                index++;
                yield return (double)fraction;
            }
        }

        static IEnumerable<double> Function3()
        {
            Fraction fraction = new Fraction(1, 1);

            while (true)
            {
                fraction.denominator *= -2;
                yield return (double)fraction;
            }
        }

        static void Main()
        {
            double epsilon = 0.01;
            
            ConvergientSeries series = new ConvergientSeries(Function1);
            Console.WriteLine(CalculateSum(series, epsilon));

            series = new ConvergientSeries(Function2);
            Console.WriteLine(CalculateSum(series, epsilon));

            series = new ConvergientSeries(Function3);
            Console.WriteLine(CalculateSum(Function3, epsilon));
        }
    }
}
